package com.dreamer.view.lottery;

import com.dreamer.domain.lottery.Activity;
import com.dreamer.domain.user.User;
import com.dreamer.service.lottery.ActivityHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import ps.mx.otter.utils.SearchParameter;
import ps.mx.otter.utils.WebUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/activity")
public class ActivityQueryController {

    @Autowired
    private ActivityHandler activityHandler;

    @RequestMapping("/index.html")
    public String index(
            @ModelAttribute("parameter") SearchParameter<Activity> parameter,
            HttpServletRequest request, Model model) {
        try {
            List<Activity> list = activityHandler.searchAllByPage(parameter);
            WebUtil.turnPage(parameter, request);
            model.addAttribute("activityList", list);
        } catch (Exception exp) {
            exp.printStackTrace();
        }
        return "lottery/activity_index";
    }

    @RequestMapping(value = "/edit.html", method = RequestMethod.GET)
    public String edit_enter(@ModelAttribute("parameter") SearchParameter<Activity> parameter, HttpServletRequest request) {
        User user = (User) WebUtil.getCurrentUser(request);
        if (user.isAdmin()) {
            return "lottery/activity_edit";
        } else {
            return "common/403";
        }

    }

    @ModelAttribute("parameter")
    public SearchParameter<Activity> preprocess(@RequestParam("id") Optional<Integer> id) {
        SearchParameter<Activity> parameter = new SearchParameter<>();
        Activity  activity;
        if (id.isPresent()) {
            activity = activityHandler.findById(id.get());
        }else {
            activity=new Activity();
        }
        parameter.setEntity(activity);
        return parameter;
    }

}
